<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 第一行 搜索添加区域 -->
      <div class="firstLine">
        <!-- 输入框 -->
        <el-input
          placeholder="请输入内容"
          v-model="queryInfo.query"
          clearable
          @clear="getUserList"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getUserList"
          ></el-button>
        </el-input>
        <!-- 添加用户按钮 -->
        <el-button type="primary" @click="addDialogVisible = true"
          >添加用户</el-button
        >
      </div>
      <!-- 第二行 用户数据列表渲染区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 使用作用域插槽渲染开关按钮 -->
        <el-table-column label="状态" width="80px">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 使用作用域插槽渲染功能按钮 -->
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="showDeleteMessageBox(scope.row)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="showSetDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 第三行 分页器区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- dialog弹出对话框区域 添加用户区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="resetAddForm"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- dialog弹出对话框区域 修改用户区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- dialog弹出对话框区域 分配角色区域 -->
    <el-dialog title="分配角色" :visible.sync="setDialogVisible" width="50%">
      <div>
        <div style="font-size: 16px">当前用户：{{ userInfo.username }}</div>
        <div style="font-size: 16px">当前角色：{{ userInfo.role_name }}</div>
        <div>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的邮箱地址'))
      }
    }
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18(0-9)|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    return {
      // 获取用户信息接口所需要的三个参数对象
      queryInfo: {
        // 搜索关键字
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示的数据
        pagesize: 2
      },
      // 用户信息
      userList: [],
      // 总数据条数
      total: 0,
      // 控制添加用户对话的隐藏与显示
      addDialogVisible: false,
      // 控制修改用户对话的隐藏与显示
      editDialogVisible: false,
      // 控制分配用户对话的隐藏与显示
      setDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户的表单数据
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      // 角色权限列表
      rolesList: [],
      // 分配角色的用户信息
      userInfo: {},
      selectedRoleId: '',
      // 添加用户的表单数据的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3到10之间' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码的长度在6到15之间' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile }
        ]
      }
    }
  },
  methods: {
    // 用户数据获取接口
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 分页器事件size-change 选择每页显示多少条的功能
    handleSizeChange(newSize) {
      // 当改变每页的显示数据条数之后，就要复制给data中的数据
      this.queryInfo.pagesize = newSize
      // 但是这样还不够，因为queryInfo是作为请求参数的，所以还需要重新请求一遍数据
      this.getUserList()
    },
    // 分页器事件current-change 选择当前第几页的数据
    handleCurrentChange(newNum) {
      // 同上
      this.queryInfo.pagenum = newNum
      this.getUserList()
    },
    // 状态改变事件mg_state
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      // 更新失败的情况
      if (res.meta.status !== 200) {
        // 由于前端的状态已经改变，所以要取反回来
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      return this.$message.success(res.meta.msg)
    },
    // 重置添加用户表单数据
    resetAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 重置修改用户表单数据
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户前的预校验
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // 当valid为false的时候，要return出去
        if (!valid) return
        // 发起添加用户的请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.addDialogVisible = !this.addDialogVisible
        this.getUserList()
        return this.$message.success(res.meta.msg)
      })
    },
    // 监听点击修改用户事件
    showEditDialog(userInfo) {
      this.editForm = userInfo
      this.editDialogVisible = true
    },
    // 修改用户前的预校验
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        // 当valid为false的时候，要return出去
        if (!valid) return
        // 发起修改用户的请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success(res.meta.msg)
      })
    },
    // 删除用户弹出对话框，是否确认
    // 如果确定res为confirm，否则为cancel
    async showDeleteMessageBox(userInfo) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete('users/' + userInfo.id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    async showSetDialog(userInfo) {
      // 在展示对话框前先调用角色列表接口
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.info(res.meta.msg)
      this.rolesList = res.data
      // console.log(res.data)
      this.userInfo = userInfo
      this.setDialogVisible = !this.setDialogVisible
    },
    async setUser() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      console.log(res)
    }
  },
  created() {
    // 页面创建就获取数据
    this.getUserList()
  }
}
</script>

<style lang="less" scpoed>
.firstLine {
  display: flex;
  justify-content: flex-start;
  .el-input {
    width: 300px;
    margin-right: 20px;
  }
}
.el-input__inner {
  box-sizing: border-box;
  height: 30px;
}
</style>
